#include "pictureitem.h"
#include <QGraphicsSceneMouseEvent>
#include <QPainter>

pictureItem::pictureItem(QGraphicsObject *parent)
    : QGraphicsObject(parent)
    , id(0)
    , type(0)
    , isPressed(false)
    , pointPercent(0.0)
    , mode(Qt::SmoothTransformation)
{

}

pictureItem::pictureItem(const QPixmap &pixmap, QGraphicsObject *parent)
    : QGraphicsObject(parent),
      type(0),
      isPressed(false),
      mode(Qt::SmoothTransformation)
{
    this->p_pixmap = pixmap;
}

int pictureItem::getId()const
{
    return id;
}
void pictureItem::setId(int id)
{
    this->id = id;
}

int pictureItem::getType()const
{
    return type;
}
void pictureItem::setType(int type)
{
    this->type = type;
}

QPointF pictureItem::getOffset()const
{
    return offset;
}
void pictureItem::setOffset(const QPointF &offset)
{
    this->offset = offset;
    this->pos();//??????????????????????????????
    if(this->offset == offset)
        return;
    prepareGeometryChange();
    this->offset = offset;
    update();
}

QPixmap pictureItem::getPixmap()const
{
    return p_pixmap;
}
void pictureItem::setPixmap(const QPixmap &pixmap)
{
    prepareGeometryChange();
    p_pixmap = pixmap;
    update();
}


void pictureItem::setTransformationMode(Qt::TransformationMode mode)
{
    this->mode = mode;
    update();
}

QRectF pictureItem::boundingRect() const
{
    if(p_pixmap.isNull())
    {
        return  QRectF();
    }
    else
    {
        return QRectF(offset, p_pixmap.size() / p_pixmap.devicePixelRatio());
    }
}

void pictureItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
    if(event->button() == Qt::LeftButton)
    {
        pressedPoint = event->pos();
        isPressed = true;
    }
}

void pictureItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
    if(event->button() == Qt::LeftButton)
    {
        //isPressed为true 且松开点和按下点都在区域内 才触发信号
        if(isPressed && boundingRect().contains(event->pos()) && boundingRect().contains(pressedPoint))
        {
            emit clicked();
            emit clickedId(getType());
            isPressed = false;
        }
    }
}

void pictureItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    Q_UNUSED(option);
    Q_UNUSED(widget);
    painter->setRenderHint(QPainter::SmoothPixmapTransform, this->mode == Qt::SmoothTransformation);
    painter->drawPixmap(offset, p_pixmap);
}
